package com.mx.zb.mng.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

public class Ip {
	
	public static String getLocalHostName() {
		String hostName;
		try {
			InetAddress addr = InetAddress.getLocalHost();
			hostName = addr.getHostName();
		} catch (Exception ex) {
			hostName = "";
		}
		return hostName;
	}

	public static String[] getAllLocalHostIP() {
		String[] ret = null;
		try {
			String hostName = getLocalHostName();
			if (hostName.length() > 0) {
				InetAddress[] addrs = InetAddress.getAllByName(hostName);
				if (addrs.length > 0) {
					ret = new String[addrs.length];
					for (int i = 0; i < addrs.length; i++) {
						ret[i] = addrs[i].getHostAddress();
					}
				}
			}

		} catch (Exception ex) {
			ret = null;
		}
		return ret;
	}
	
	public static String getOutterIp(){
		return getRealIp(true);
	}
	
	public static String getInnerIp(){
		return getRealIp(false);
	}
	
	public static String getRealIp(boolean isOutterIp)  {
        if (isOutterIp) {
            return getAllIp()[0];
        } else {
            return getAllIp()[1];
        }
    }
	
	/**
	 * 获取内外网的网卡ip，不含全部
	 * @return 字符串数组，0是外网的，1是内网的
	 */
	public static String[] getAllIp(){
        try {
			String localip = null;// 本地IP，如果没有配置外网IP则返回它
			String netip = null;// 外网IP
 
			Enumeration<NetworkInterface> netInterfaces = 
			    NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
//        boolean finded = false;// 是否找到外网IP
			while (netInterfaces.hasMoreElements()) {
			    NetworkInterface ni = netInterfaces.nextElement();
			    Enumeration<InetAddress> address = ni.getInetAddresses();
			    while (address.hasMoreElements()) {
			        ip = address.nextElement();
			        if (!ip.isSiteLocalAddress() 
			                && !ip.isLoopbackAddress() 
			                && ip.getHostAddress().indexOf(":") == -1) {// 外网IP                    
			            if(netip==null){
			            	netip = ip.getHostAddress();
			        	}else {
			        		netip += "," + ip.getHostAddress();
			        	}
			        } else  if (ip.isSiteLocalAddress() 
			                && !ip.isLoopbackAddress() 
			                && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
			        	if(localip==null){
			        		localip = ip.getHostAddress();
			        	}else {
			        		localip += "," + ip.getHostAddress();
			        	}
			            
			        }
			    }
			}
    
			return new String[]{netip,localip};
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e.getCause());
		}
    }
	
	/**
	 * 获取客户端的ip，考虑了反向代理等问题
	 * @param request
	 * @return
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		String ipAddress = null;
		// ipAddress = this.getRequest().getRemoteAddr();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}

		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
															// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	public static void main(String[] args) {
		 System.out.println(getLocalHostName());
		 
		 System.out.println("===========================");
		 
		 String[] ips=getAllLocalHostIP();
		 for(String ip:ips){
			 System.out.println(ip);
		 }
		 
		 System.out.println("===========================");
		 
		 System.out.println("outter IP:"+getOutterIp());
		 
		 System.out.println("inner IP:"+getInnerIp());
		
		 /**
		  * pns外网服务器1：
		  * 
iZ239s2cnoqZ
===========================
10.160.4.162
===========================
outter IP:112.124.8.178
inner IP:10.160.4.162
		  *
		  * 本机（多加了一个IP）：
		  * 
yanfa-PC
===========================
10.0.0.29
192.168.1.130
fe80:0:0:0:1c54:4125:947d:b7f0%11
===========================
outter IP:null
inner IP:192.168.1.130,10.0.0.29
		  *
		  */
	}
}
